package com.base.server.modules.power.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.server.modules.power.entity.RolePermissionRelation;
import com.base.server.modules.power.entity.RolePermissionRelationVo;
import com.base.server.modules.power.mapper.RolePermissionRelationMapper;
import com.base.server.modules.power.service.RolePermissionRelationService;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 角色与权限关联表 服务实现类
 * </p>
 *
 * @author ostrich
 * @since 2019-11-28
 */
@Service
public class RolePermissionRelationServiceImpl extends ServiceImpl<RolePermissionRelationMapper, RolePermissionRelation> implements RolePermissionRelationService {

    @Resource
    private RolePermissionRelationMapper rolePermissionRelationMapper;

    /**
     * 保存角色和权限关联关系
     *
     * @param param
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public void save(RolePermissionRelationVo param) {
        HashMap<String, Object> column = Maps.newHashMap();
        column.put("role_id", param.getRoleId());
        column.put("type", param.getType());
        rolePermissionRelationMapper.deleteByMap(column);
        final RolePermissionRelation[] relation = {null};
        String permissionIds = param.getPermissionId();
        if (StringUtils.isNoneBlank(permissionIds)) {
            Arrays.asList(permissionIds.split(",")).forEach(o -> {
                relation[0] = new RolePermissionRelation();
                relation[0].setPermissionId(o);
                relation[0].setRoleId(param.getRoleId());
                relation[0].setType(param.getType());
                rolePermissionRelationMapper.insert(relation[0]);
            });
        }
    }

    /**
     * 根据角色id查询拥有的权限信息
     *
     * @param id
     * @return
     */
    @Override
    public List<RolePermissionRelation> getOne(String id) {
        HashMap<String, Object> column = Maps.newHashMap();
        column.put("role_id", id);
        return rolePermissionRelationMapper.selectByMap(column);
    }
}
